//
//  HealthKnowledgeListViewController.m
//  LoveHealth
//
//  Created by 陈永坤 on 14-9-20.
//  Copyright (c) 2014年 lanou. All rights reserved.
//

#import "HealthKnowledgeListViewController.h"
#import "HealthKnowledgeList.h"
#import "UIImageView+WebCache.h"
#import "HealthKnowledgeDetailViewController.h"
#import "MONActivityIndicatorView.h"
//#import <AudioToolbox/AudioToolbox.h>
#import "SearchViewController.h"

#import "MJRefresh.h"
#import "NetHelper.h"
#import "KGStatusBar.h"
@interface HealthKnowledgeListViewController ()<MONActivityIndicatorViewDelegate>

@property (nonatomic,retain)TMQuiltView * qtmquitView;
@property (nonatomic,retain)NSMutableArray * knowledgeArray;
@property (nonatomic,assign)NSInteger page;
@property (nonatomic,retain)MONActivityIndicatorView  * indicatorView;
@end

@implementation HealthKnowledgeListViewController

- (void)dealloc
{
    self.qtmquitView = nil;
    self.knowledgeClass = nil;
    self.indicatorView = nil;
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = self.knowledgeClass.name;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.page = 1;
    CGRect frame = [[UIScreen mainScreen]bounds];
    _qtmquitView = [[TMQuiltView alloc] initWithFrame:CGRectMake(frame.origin.x, frame.origin.y+64, frame.size.width    , frame.size.height - 64 -49)];
	_qtmquitView.delegate = self;
	_qtmquitView.dataSource = self;

	[self.view addSubview:_qtmquitView];
	self.knowledgeArray = [NSMutableArray arrayWithCapacity:20];
    
    
    //设置加载loading
    [self setupActivityIndicator];
    [self.indicatorView stopAnimating];
    
	[self p_sendReuqest:self.page];
    //设置下拉刷新，下拉加载更多
    [self setupRefresh];
    
    
    UIBarButtonItem * searchButtonTtem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone  target:self action:@selector(didClickSearchButtonTtemAction:)];
    self.navigationItem.rightBarButtonItem = searchButtonTtem;
    [searchButtonTtem release];

}

- (void)didClickSearchButtonTtemAction:(UIBarButtonItem *)searchButton
{
    SearchViewController * searchVC = [[SearchViewController alloc]init];
    searchVC.type = knowledgeType;
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}



//下拉刷新，上拉显示更多
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.qtmquitView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    //[self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.qtmquitView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.qtmquitView.headerPullToRefreshText = @"下拉可以刷新了";
    self.qtmquitView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.qtmquitView.headerRefreshingText = @"正在帮你刷新中,不客气";

    
    self.qtmquitView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.qtmquitView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.qtmquitView.footerRefreshingText = @"正在帮你加载中,不客气";
}

- (void)headerRereshing
{
    //[self.knowledgeArray removeAllObjects];
    [self p_sendReuqest:1];
    [self.qtmquitView reloadData];
    [self.qtmquitView headerEndRefreshing];
}

- (void)footerRereshing
{
    
    self.page++;
    [self p_sendReuqest:self.page];
    
    [self.qtmquitView reloadData];
    [self.qtmquitView footerEndRefreshing];
}



- (void)p_sendReuqest:(NSInteger )page
{
    
    [self.indicatorView startAnimating];
    
    //拼接网址
    NSString * urlString =[[NSString alloc]initWithFormat:@"%@?id=%@&page=%ld",APIHealthKnowledgeList,self.knowledgeClass.ID,page];
    
   // NSURL * url = [NSURL URLWithString:urlString];
    
    
    __block  HealthKnowledgeListViewController * knowledgeListVC = self;
    [[NetHelper shareInstance]loadingDataWithUrlString:urlString urlExpireInSeconds:30 download:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        if (data != nil && connectionError == nil) {
            NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            //数据处理
            NSArray * sourceArray = sourceDic[@"yi18"];
            if (page == 1) {
                [knowledgeListVC.knowledgeArray removeAllObjects];
            }
            for (NSDictionary * dic in sourceArray) {
                
                HealthKnowledgeList * knowledgeList = [[HealthKnowledgeList alloc]init];
                [knowledgeList setValuesForKeysWithDictionary:dic];
                
                [knowledgeListVC.knowledgeArray addObject:knowledgeList];
                [knowledgeList release];
                
            }

        }else{
             [KGStatusBar showErrorWithStatus:kNetErrorMessage];
        }
        
        
        [_qtmquitView reloadData];
        [_indicatorView stopAnimating];
        
        //刷新声音
//        NSString *path = [[NSBundle mainBundle] pathForResource:@"didi" ofType:@"wav"];
//        NSURL *url = [NSURL fileURLWithPath:path];
//        SystemSoundID soundId;
//        AudioServicesCreateSystemSoundID((CFURLRef)url, &soundId);
//        AudioServicesPlaySystemSound(soundId);
    }];
    

    /*
    
    //建立网络连接
    __block  HealthKnowledgeListViewController * knowledgeListVC = self;
    
    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        //解析数据
        NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        //数据处理
        NSArray * sourceArray = sourceDic[@"yi18"];
        
        //NSMutableArray * array = [NSMutableArray arrayWithCapacity:20];
//        if (page == 1) {
//            [self.knowledgeArray removeAllObjects];
//        }
        for (NSDictionary * dic in sourceArray) {
            
            HealthKnowledgeList * knowledgeList = [[HealthKnowledgeList alloc]init];
            [knowledgeList setValuesForKeysWithDictionary:dic];
            
            [knowledgeListVC.knowledgeArray addObject:knowledgeList];
            [knowledgeList release];
            
            
            
//            NSString * url = APIImageURL(knowledgeList.img);
//            UIImageView * imageView = [[UIImageView alloc]init];
//            [imageView setImageWithURL:[NSURL URLWithString:url] success:^(UIImage *image, BOOL cached) {
//                
//                knowledgeList.showImage = image;
//                knowledgeList.ImgWidth = image.size.width;
//                knowledgeList.ImgHeight = image.size.height;
//                [knowledgeListVC.knowledgeArray addObject:knowledgeList];
//                NSLog(@"%@",knowledgeList.className);
//                [knowledgeList release];
//                [knowledgeListVC.qtmquitView reloadData];
//            } failure:nil];
            
            
        }
        
        [_qtmquitView reloadData];
        [_indicatorView stopAnimating];
       
        //刷新声音
        NSString *path = [[NSBundle mainBundle] pathForResource:@"didi" ofType:@"wav"];
        NSURL *url = [NSURL fileURLWithPath:path];
        SystemSoundID soundId;
        AudioServicesCreateSystemSoundID((CFURLRef)url, &soundId);
        AudioServicesPlaySystemSound(soundId);
        
        //[self createHeaderView];
        //[self performSelector:@selector(testFinishedLoadData) withObject:nil afterDelay:0.0f];
    }];*/
    
}

//设置loading
- (void)setupActivityIndicator
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.delegate = self; //设置代理
    _indicatorView.numberOfCircles = 6; //圆圈个数
    _indicatorView.radius = 10;//圆圈大小
    _indicatorView.internalSpacing = 3;//圆圈之间的间距
    _indicatorView.center = self.view.center;
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}
//指示器 代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    CGFloat red   = (arc4random() % 256)/255.0;
    CGFloat green = (arc4random() % 256)/255.0;
    CGFloat blue  = (arc4random() % 256)/255.0;
    CGFloat alpha = 1.0f;
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}




- (HealthKnowledgeList *)knowledgeAtIndexPath:(NSIndexPath *)indexPath {
    
    return [self.knowledgeArray objectAtIndex:indexPath.row];
    
}

- (NSInteger)quiltViewNumberOfCells:(TMQuiltView *)TMQuiltView {
    return [self.knowledgeArray count];
}

- (TMQuiltViewCell *)quiltView:(TMQuiltView *)quiltView cellAtIndexPath:(NSIndexPath *)indexPath {
    HealthKnowledgeListViewCell *cell = (HealthKnowledgeListViewCell *)[quiltView dequeueReusableCellWithReuseIdentifier:@"Cell"];
    if (!cell) {
        cell = [[[HealthKnowledgeListViewCell alloc] initWithReuseIdentifier:@"Cell"] autorelease];
    }
    
    //cell.photoView.image = [self knowledgeAtIndexPath:indexPath].showImage;
    
    NSString * url = APIImageURL([self knowledgeAtIndexPath:indexPath].img);
    
    [cell.photoView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:kPlaceholderImage];
    //[cell.photoView setImageWithURL:[NSURL URLWithString:url]];
    cell.titleLabel.text = [self knowledgeAtIndexPath:indexPath].title;
    return cell;
}

#pragma mark - TMQuiltViewDelegate

- (NSInteger)quiltViewNumberOfColumns:(TMQuiltView *)quiltView {
	
    
    if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft
        || [[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)
	{
        return 3;
    } else {
        return 2;
    }
}

- (CGFloat)quiltView:(TMQuiltView *)quiltView heightForCellAtIndexPath:(NSIndexPath *)indexPath
{
    return [self knowledgeAtIndexPath:indexPath].ImgHeight / [self quiltViewNumberOfColumns:quiltView];
}

- (void)quiltView:(TMQuiltView *)quiltView didSelectCellAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"index:%ld",indexPath.row);
    
    HealthKnowledgeDetailViewController * knowledgeDVC = [[HealthKnowledgeDetailViewController alloc]init];
    
    HealthKnowledgeListViewCell * cell = (HealthKnowledgeListViewCell *)[quiltView cellAtIndexPath:indexPath];
    [self knowledgeAtIndexPath:indexPath].showImage = cell.photoView.image;

    knowledgeDVC.knowledgeList = [self knowledgeAtIndexPath:indexPath];
    [self.navigationController pushViewController:knowledgeDVC animated:YES];
    [knowledgeDVC release];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
